<template>
  <div class="upload-file">
    <el-upload class="upload-demo" drag :action="props.action" multiple :headers="headers" :on-remove="handleRemoveFile"
      :on-success="setFiles" v-model:file-list="files">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        拖拽文件上传 或 <em>点击上传文件</em>
      </div>
      <!-- <template #tip>
        <div class="el-upload__tip">
          jpg/png files with a size less than 500kb
        </div>
      </template> -->
    </el-upload>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, } from "vue"
import { UploadFilled } from '@element-plus/icons-vue'
import Service from '@/utils/axios'
import { ElMessage, ElMessageBox } from "element-plus";
import "element-plus/es/components/message/style/css"; // 按需引入ElMessage样式失败，手动引入
import "element-plus/es/components/message-box/style/css";

const files = ref()
// 向父组件传文件数据
const emit = defineEmits(['updateFiles'])
// 从父组件获取上传地址
const props = defineProps({
  action: {
    type: String, // 数据类型
    required: true, // 必传
  }
})

// 向父组件传files
const setFiles = () => {
  let urlArr: string[] = [];
  files.value.forEach((el: any) => {
    urlArr.push(el.response.simpleUrl);
  });
  emit('updateFiles', urlArr as string[]);
}

// 上传文件时的请求头
let headers = reactive({
  Authorization: localStorage.getItem("token"),
});

// 删除文件的方法
const handleRemoveFile = (uploadFile: any, uploadFiles: any) => {
  // console.log('uploadFile', uploadFile)
  // console.log('uploadFiles', uploadFiles)
  Service.post('/bkapi/api/deletefilePublishEnt', {
    filename: uploadFile.response?.filename,
    fileUrl: uploadFile.response?.fileUrl
  }).then((res: any) => {
    // console.info('res', res)
    if (res.data?.status === 200) {
      ElMessage({
        showClose: true,
        message: res.data?.data,
        type: 'success',
      })
    } else {
      ElMessage({
        showClose: true,
        message: res.data?.data,
        type: 'error',
      })
    }

  })
}


</script>

<style lang="less" scoped>
.upload-file {
  width: 100%;
}
</style>